package casia.isiteam.springbootshiro.controller.longin;

import casia.isiteam.springbootshiro.properties.result.HttpResult;
import casia.isiteam.springbootshiro.service.UserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;

/**
 * Author wzy
 * Date 2017/7/27 21:07
 */
@RestController
public class login {
    private final static Logger logger = LoggerFactory.getLogger(login.class);

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping(value = "home")
    public Object home(HttpServletRequest request) throws Exception{
        return HttpResult.error(777,"请重新登陆！","userlogin");
    }

    @RequestMapping(value = "userlogin", method = RequestMethod.GET)
    public Object login(HttpServletRequest request,String username, String password) throws Exception{
        if( StringUtils.isEmpty(username) && StringUtils.isEmpty(password) ){
            return HttpResult.error(777,"请重新登录！");
        }
        if( StringUtils.isEmpty(username) || StringUtils.isEmpty(password) ){
            return HttpResult.error(400,"参数不能为空！");
        }
        LoginIP( request, username );
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token  = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);
            //设置会话的过期时间--ms,默认是30分钟，设置负数表示永不过期
            Session session = subject.getSession();
            session.setAttribute("subject",user);//放入会话信息
            session.setTimeout(60*60*1000);
//            UserInfo user = userInfoService.findByUsername(username);
            logger.info("登录成功！");
            return HttpResult.sucess("登录成功！");
        }catch(UnknownAccountException uae){
            logger.info("对用户[" + username + "]进行登录验证..验证未通过,未知账户");
            return   HttpResult.error(400, "未知账户");
        }catch(IncorrectCredentialsException ice){
            logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误的凭证");
            return   HttpResult.error(400, "密码不正确");
        }catch(LockedAccountException lae){
            logger.info("对用户[" + username + "]进行登录验证..验证未通过,账户已锁定");
            return   HttpResult.error(400, "账户已锁定");
        }catch(ExcessiveAttemptsException eae){
            logger.info("对用户[" + username + "]进行登录验证..验证未通过,错误次数大于5次,账户已锁定");
            return   HttpResult.error(400, "用户名或密码错误次数大于5次,账户已锁定");
        }catch (DisabledAccountException sae){
            logger.info("对用户[" + username + "]进行登录验证..验证未通过,帐号已经禁止登录");
            return   HttpResult.error(400, "帐号已经禁止登录");
        }catch(AuthenticationException ae){
            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景
            logger.info("对用户[" + username + "]进行登录验证..验证未通过,堆栈轨迹如下");
            ae.printStackTrace();
            return   HttpResult.error(400, "用户名或密码不正确");
        }
    }
    @RequestMapping(value="/userlogout")
    public Object logout(RedirectAttributes redirectAttributes ){
        //使用权限管理工具进行用户的退出，跳出登录，给出提示信息
        SecurityUtils.getSubject().logout();
        redirectAttributes.addFlashAttribute("message", "您已安全退出");
        return HttpResult.sucess( redirectAttributes.getFlashAttributes());
    }

    private static void LoginIP (HttpServletRequest request,String UserName){
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        logger.info("用户："+UserName+"，正在尝试登录，来源IP："+ip+" !");
    }
}
